package ooday04;
/** 多态的演示 */
public class PolymorphicDemo {
    public static void main(String[] args) {
        //演示向上造型：
       /* Dog o1 = new Dog("旺财", 2, "黄色");
        //dog.name/age/color/swim()/lookHome()/eat()/drink()
        o1.eat();
        o1.drink();
        o1.lookHome();
        o1.swim();

        Animal o2 = new Dog("旺财", 2, "黄色");
        //animal.name/age/color/eat()/drink()
        o2.eat();
        o2.drink();

        Swim o3 = new Dog("旺财", 2, "黄色");
        //swim()
        o3.swim();**/

        //演示向上造型（多态）的第1点应用：
       /* Master master = new Master();
        Dog dog = new Dog("旺财", 2, "黄色");
        //Animal dog =new Dog("旺财", 2, "黄色");
        Chick chick = new Chick("小鸡", 1, "白色");
        Fish fish = new Fish("小鱼", 1, "蓝色");
        master.feed(dog); //在传参时，编译器会自动将Dog对象转换为Animal对象，自动向上造型
        master.feed(chick);
        master.feed(fish);*/

        //演示向上造型（多态）的第2点应用：
        //Animal animal = new Animal();//抽象类不能实例化
        Animal[] animals = new Animal[3];//动态初始化
        animals[0] = new Dog("旺财", 2, "黄色");//动态初始化,向上造型
        animals[1] = new Chick("小鸡", 1, "白色");//动态初始化，向上造型
        animals[2] = new Fish("小鱼", 1, "蓝色");//动态初始化，向上造型

        for (int i = 0; i < animals.length; i++){
            //System.out.println(animals[i].name); //   instanceof
            //animals[i].eat(); //动态绑定,让每一个动物都能吃
            //animals[i].drink();//动态绑定,让每一个动物都能喝
            if (animals[i] instanceof Dog){
                Dog dog = (Dog)animals[i];
                dog.lookHome();
            }
            if (animals[i] instanceof Chick){
                Chick chick = (Chick)animals[i];
                chick.fly();
            }
            if (animals[i] instanceof Swim){
                Swim s = (Swim)animals[i];
                s.swim();
            }
        }
        //演示强制转换的条件：
        Animal o = new Dog("旺财", 2, "黄色");
        Dog g = (Dog)o;
        //Fish f = (Fish)o;//编译不通过 因为animal对象不是Fish类型 有异常ClassCastException
        System.out.println(o instanceof Fish);
        Swim swim = (Swim)o;
        //Fish fish = (Fish)animal;//编译不通过 因为animal对象不是Fish类型 有异常ClassCastException
       /* System.out.println(g instanceof Swim);//true
        System.out.println(g instanceof Animal);//true
        System.out.println(g instanceof Dog);//true
        System.out.println(o instanceof Dog);//true*/


    }

}
